<?php
class CWebUser
{
	public $guestName='Guest';	
	public $loginUrl=array('login');	
	private $_keyPrefix;
	private $_req;
	private $_session;
	 
	 
	public function setRequest(&$_req)
	{
		$this->_req=$_req;
	}	
	
	public function setSession(&$_session)
	{
		$this->_session=$_session;
	}
	
	public function getRequest()
	{
		return $this->_req;
	}	
	
	public function getSession()
	{
		return $this->_session;
	}
		
	public function init()
	{		
		$this->getSession()->open();
		$this->_keyPrefix=md5('Deepr.'.get_class($this).'.'.$this->getId());
	}

	
	public function login($id,$username)
	{		
		$this->changeIdentity($id,$username);
		return !$this->getIsGuest();
	}

	
	public function logout($destroySession=true)
	{
		if($destroySession)
				$this->getSession()->destroy();
			else
				$this->clearStates();
	}

	
	public function getIsGuest()
	{
		return $this->getState('__id')===null;
	}

	
	public function getId()
	{
		return $this->getState('__id');
	}

	
	public function setId($value)
	{
		$this->setState('__id',$value);
	}

	
	public function getName()
	{
		if(($name=$this->getState('__name'))!==null)
			return $name;
		else
			return $this->guestName;
	}

	
	public function setName($value)
	{
		$this->setState('__name',$value);
	}

	
	public function getReturnUrl($defaultUrl=null)
	{
		return $this->getState('__returnUrl', $defaultUrl===null ? $this->getRequest()->getScriptUrl() : CHtml::normalizeUrl($defaultUrl));
	}

	
	public function setReturnUrl($value)
	{
		$this->setState('__returnUrl',$value);
	}

	

	public function getState($key,$defaultValue=null)
	{
		$key=$this->_keyPrefix.$key;
		return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
	}

	public function setState($key,$value,$defaultValue=null)
	{
		$key=$this->_keyPrefix.$key;
		if($value===$defaultValue)
			unset($_SESSION[$key]);
		else
			$_SESSION[$key]=$value;
	}

	public function hasState($key)
	{
		$key=$this->_keyPrefix.$key;
		return isset($_SESSION[$key]);
	}
	
	public function clearStates()
	{
		$keys=array_keys($_SESSION);
		$prefix=$this->_keyPrefix;
		$n=strlen($prefix);
		foreach($keys as $key)
		{
			if(!strncmp($key,$prefix,$n))
				unset($_SESSION[$key]);
		}
	}
	
	protected function changeIdentity($id,$name)
	{
		$this->getSession()->regenerateID(true);
		$this->setId($id);
		$this->setName($name);
	}
	
}
